<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户聊天记录</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .chat-container {
            max-width: 1000px;
            margin: 0 auto;
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }

        .header h1 {
            font-size: 2.5rem;
            margin-bottom: 10px;
            font-weight: 700;
        }

        .header p {
            font-size: 1.1rem;
            opacity: 0.9;
        }

        .back-to-detail {
            position: absolute;
            top: 20px;
            left: 20px;
            background: rgba(255, 255, 255, 0.2);
            color: white;
            border: none;
            padding: 12px 20px;
            border-radius: 25px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-block;
        }

        .back-to-detail:hover {
            background: rgba(255, 255, 255, 0.3);
            transform: translateY(-2px);
        }

        .candidate-info {
            background: #f8f9fa;
            padding: 30px;
            border-bottom: 1px solid #e9ecef;
        }

        .candidate-card {
            display: flex;
            align-items: center;
            gap: 20px;
            background: white;
            padding: 25px;
            border-radius: 15px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
        }

        .candidate-avatar {
            width: 80px;
            height: 80px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 2rem;
            font-weight: bold;
        }

        .candidate-details h2 {
            color: #2c3e50;
            font-size: 1.8rem;
            margin-bottom: 8px;
        }

        .candidate-details p {
            color: #6c757d;
            margin-bottom: 5px;
            font-size: 1rem;
        }

        .candidate-stats {
            display: flex;
            gap: 30px;
            margin-top: 15px;
        }

        .stat-item {
            text-align: center;
        }

        .stat-value {
            font-size: 1.5rem;
            font-weight: bold;
            color: #667eea;
        }

        .stat-label {
            font-size: 0.9rem;
            color: #6c757d;
            margin-top: 5px;
        }

        .chat-messages {
            padding: 30px;
            max-height: 600px;
            overflow-y: auto;
        }

        .message-item {
            margin-bottom: 20px;
            display: flex;
            align-items: flex-start;
            gap: 15px;
        }

        .message-ai {
            flex-direction: row-reverse;
        }

        .message-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 0.9rem;
            font-weight: bold;
            color: white;
            flex-shrink: 0;
        }

        .message-ai .message-avatar {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }

        .message-candidate .message-avatar {
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
        }

        .message-content {
            max-width: 70%;
            padding: 15px 20px;
            border-radius: 20px;
            position: relative;
            word-wrap: break-word;
        }

        .message-ai .message-content {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-bottom-right-radius: 5px;
        }

        .message-candidate .message-content {
            background: #f8f9fa;
            color: #2c3e50;
            border: 1px solid #e9ecef;
            border-bottom-left-radius: 5px;
        }
        
        .message-salary-related .message-content {
            background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);
            color: #92400e;
            border: 2px solid #f59e0b;
            position: relative;
        }
        
        .message-salary-related .message-content::before {
            content: '💰';
            position: absolute;
            top: -8px;
            right: -8px;
            background: #f59e0b;
            color: white;
            border-radius: 50%;
            width: 20px;
            height: 20px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 12px;
        }

        .message-time {
            font-size: 0.8rem;
            opacity: 0.7;
            margin-top: 5px;
            text-align: right;
        }

        .message-candidate .message-time {
            text-align: left;
        }

        .loading {
            text-align: center;
            padding: 50px;
            color: #6c757d;
            font-size: 1.1rem;
        }

        .error {
            text-align: center;
            padding: 50px;
            color: #dc3545;
            font-size: 1.1rem;
        }

        .no-messages {
            text-align: center;
            padding: 50px;
            color: #6c757d;
            font-size: 1.1rem;
        }

        .no-messages i {
            font-size: 3rem;
            margin-bottom: 20px;
            opacity: 0.5;
        }

        /* 滚动条样式 */
        .chat-messages::-webkit-scrollbar {
            width: 6px;
        }

        .chat-messages::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 3px;
        }

        .chat-messages::-webkit-scrollbar-thumb {
            background: #c1c1c1;
            border-radius: 3px;
        }

        .chat-messages::-webkit-scrollbar-thumb:hover {
            background: #a8a8a8;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .chat-container {
                margin: 10px;
                border-radius: 15px;
            }

            .header h1 {
                font-size: 2rem;
            }

            .candidate-card {
                flex-direction: column;
                text-align: center;
            }

            .candidate-stats {
                justify-content: center;
            }

            .message-content {
                max-width: 85%;
            }
        }
    </style>
</head>
<body>
    <div class="chat-container">
        <div class="header">
            <a href="javascript:void(0)" class="back-to-detail" onclick="goBackToDetail()">
                ← 返回详情页
            </a>
            <h1>💬 用户聊天记录</h1>
            <p>查看与候选人的详细对话内容</p>
        </div>

        <div class="candidate-info" id="candidate-info">
            <div class="loading">正在加载用户信息...</div>
        </div>

        <div class="chat-messages" id="chat-messages">
            <div class="loading">正在加载聊天记录...</div>
        </div>
    </div>

    <script>
        // 全局变量
        let chatData = null;
        let candidateId = null;

        // 页面加载完成后执行
        document.addEventListener('DOMContentLoaded', function() {
            loadUserChatData();
        });

        /**
         * 加载用户聊天数据
         */
        async function loadUserChatData() {
            try {
                console.log('[用户聊天] ========== 开始加载聊天数据 ==========');
                
                // 获取URL参数
                candidateId = getParameter('candidate_id');
                console.log('[用户聊天] 候选人ID:', candidateId);
                
                if (!candidateId) {
                    console.error('[用户聊天] 缺少candidate_id参数');
                    showError('缺少用户ID参数');
                    return;
                }

                // 调用API获取聊天记录
                console.log('[用户聊天] 正在调用API获取聊天记录...');
                chatData = await getUserChatRecords(candidateId);
                
                console.log('[用户聊天] 成功获取聊天数据:', chatData);
                
                // 显示数据
                displayCandidateInfo(chatData.candidate);
                displayChatMessages(chatData.messages);
                
                console.log('[用户聊天] ========== 聊天数据加载完成 ==========');
                
            } catch (error) {
                console.error('[用户聊天] 加载用户聊天数据失败:', error);
                showError('加载聊天记录失败: ' + error.message);
            }
        }

        /**
         * 获取用户聊天记录
         * 调用后端API获取真实的聊天记录
         */
        async function getUserChatRecords(candidateId) {
            console.log('[API调用] 开始调用 /api/candidate-messages');
            console.log('[API调用] 参数: candidate_id=' + candidateId);
            
            try {
                const apiUrl = `/api/candidate-messages?candidate_id=${candidateId}`;
                console.log('[API调用] 请求URL:', apiUrl);
                
                const response = await fetch(apiUrl, {
                    method: 'GET',
                    headers: {
                        'Accept': 'application/json'
                    }
                });
                
                console.log('[API调用] 响应状态码:', response.status);
                
                if (!response.ok) {
                    const errorData = await response.json();
                    console.error('[API调用] API返回错误:', errorData);
                    throw new Error(errorData.error || `API请求失败 (${response.status})`);
                }
                
                const responseData = await response.json();
                console.log('[API调用] 响应数据:', responseData);
                
                if (!responseData.success) {
                    console.error('[API调用] API返回失败:', responseData.error);
                    throw new Error(responseData.error || 'API请求失败');
                }
                
                const data = responseData.data;
                console.log('[API调用] 解析后的数据:');
                console.log('  - 候选人:', data.candidate?.name);
                console.log('  - 总消息数:', data.total_messages);
                console.log('  - AI消息数:', data.ai_messages);
                console.log('  - 候选人消息数:', data.candidate_messages);
                
                // 返回标准格式的数据
                return {
                    candidate: data.candidate,
                    messages: data.messages || [],
                    total_messages: data.total_messages || 0,
                    ai_messages: data.ai_messages || 0,
                    candidate_messages: data.candidate_messages || 0
                };
                
            } catch (error) {
                console.error('[API调用] 获取聊天记录失败:', error);
                throw error;
            }
        }

        /**
         * 显示候选人信息
         */
        function displayCandidateInfo(candidate) {
            if (!candidate) {
                document.getElementById('candidate-info').innerHTML = 
                    '<div class="error">用户不存在</div>';
                return;
            }

            const candidateInfo = document.getElementById('candidate-info');
            candidateInfo.innerHTML = `
                <div class="candidate-card">
                    <div class="candidate-avatar">
                        ${candidate.name ? candidate.name.charAt(0) : '?'}
                    </div>
                    <div class="candidate-details">
                        <h2>${candidate.name || '未知用户'}</h2>
                        <p><strong>电话:</strong> ${candidate.phone || '未提供'}</p>
                        <p><strong>邮箱:</strong> ${candidate.email || '未提供'}</p>
                        <p><strong>注册时间:</strong> ${candidate.created_at || '未知'}</p>
                    </div>
                </div>
                <div class="candidate-stats">
                    <div class="stat-item">
                        <div class="stat-value">${chatData.total_messages || 0}</div>
                        <div class="stat-label">总消息数</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-value">${chatData.ai_messages || 0}</div>
                        <div class="stat-label">AI消息</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-value">${chatData.candidate_messages || 0}</div>
                        <div class="stat-label">候选人消息</div>
                    </div>
                </div>
            `;
        }

        /**
         * 显示聊天消息
         */
        function displayChatMessages(messages) {
            const chatMessages = document.getElementById('chat-messages');
            
            if (!messages || messages.length === 0) {
                chatMessages.innerHTML = `
                    <div class="no-messages">
                        <div>💬</div>
                        <div>暂无聊天记录</div>
                    </div>
                `;
                return;
            }

            let messagesHtml = '';
            messages.forEach(message => {
                const isAI = message.sender === '我';
                const messageClass = isAI ? 'message-ai' : 'message-candidate';
                const avatarText = isAI ? 'AI' : '用户';
                
                // 检查是否是薪资相关消息
                const isSalaryRelated = checkSalaryRelated(message.content);
                const salaryClass = isSalaryRelated ? 'message-salary-related' : '';
                
                messagesHtml += `
                    <div class="message-item ${messageClass} ${salaryClass}">
                        <div class="message-avatar">${avatarText}</div>
                        <div class="message-content">
                            <div>${message.content}</div>
                            <div class="message-time">${formatMessageTime(message.created_at)}</div>
                        </div>
                    </div>
                `;
            });

            chatMessages.innerHTML = messagesHtml;
            
            // 滚动到底部
            chatMessages.scrollTop = chatMessages.scrollHeight;
        }

        /**
         * 格式化消息时间
         */
        function formatMessageTime(timeStr) {
            if (!timeStr) return '';
            
            try {
                const date = new Date(timeStr);
                const now = new Date();
                const diff = now - date;
                
                // 如果是今天
                if (diff < 24 * 60 * 60 * 1000 && date.getDate() === now.getDate()) {
                    return date.toLocaleTimeString('zh-CN', { 
                        hour: '2-digit', 
                        minute: '2-digit' 
                    });
                }
                
                // 如果是昨天
                const yesterday = new Date(now);
                yesterday.setDate(yesterday.getDate() - 1);
                if (date.getDate() === yesterday.getDate()) {
                    return '昨天 ' + date.toLocaleTimeString('zh-CN', { 
                        hour: '2-digit', 
                        minute: '2-digit' 
                    });
                }
                
                // 其他情况显示完整日期时间
                return date.toLocaleString('zh-CN', {
                    year: 'numeric',
                    month: '2-digit',
                    day: '2-digit',
                    hour: '2-digit',
                    minute: '2-digit'
                });
            } catch (error) {
                return timeStr;
            }
        }

        /**
         * 显示错误信息
         */
        function showError(message) {
            document.getElementById('candidate-info').innerHTML = 
                `<div class="error">${message}</div>`;
            document.getElementById('chat-messages').innerHTML = 
                `<div class="error">${message}</div>`;
        }

        /**
         * 返回详情页
         */
        function goBackToDetail() {
            console.log('[导航] 返回详情页');
            
            // 尝试从URL参数获取来源页面
            const from = getParameter('from');
            console.log('[导航] 来源页面参数:', from);
            
            if (from) {
                // 如果有明确的来源页面参数，跳转到该页面
                console.log('[导航] 跳转到来源页面:', from);
                window.location.href = from;
                return;
            }
            
            // 否则尝试使用浏览器历史记录返回
            const referrer = document.referrer;
            console.log('[导航] Referrer:', referrer);
            
            if (referrer && referrer !== window.location.href) {
                // 如果有来源页面，使用history.back()
                console.log('[导航] 使用history.back()返回');
                window.history.back();
            } else {
                // 默认返回主页
                console.log('[导航] 默认返回主页');
                window.location.href = 'index.html';
            }
        }

        /**
         * 获取URL参数
         */
        function getParameter(name) {
            const urlParams = new URLSearchParams(window.location.search);
            return urlParams.get(name);
        }
        
        /**
         * 检查消息是否包含薪资信息
         */
        function checkSalaryRelated(content) {
            if (!content) return false;
            
            // 薪资相关关键词
            const salaryKeywords = [
                '工资', '薪资', '薪水', '待遇', '收入', '报酬', '元', '钱', 
                '日结', '月结', '保底', '提成', '佣金', '奖金', '分成',
                '万元', 'k', 'K', '工钱', '费用', '时薪', '底薪'
            ];
            
            // 检查是否包含薪资关键词
            return salaryKeywords.some(keyword => content.includes(keyword));
        }
    </script>
</body>
</html>
